package com.motong.gongdan.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.motong.gongdan.entity.AssemblyWorkOrderDetail;
import com.motong.gongdan.enums.ObjectType;
import com.motong.gongdan.mapper.AssemblyWorkOrderDetailMapper;
import com.motong.gongdan.util.ColumnUtils;
import com.motong.gongdan.vo.H5Vo.Dashboard.vo.ProcessStatisticsVo;
import com.motong.gongdan.vo.system.AssemblyWorkOrder.vo.AssemblyDetailProductVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class AssemblyWorkOrderDetailService extends ServiceImpl<AssemblyWorkOrderDetailMapper, AssemblyWorkOrderDetail> {

    @Resource
    private CustomFieldService customFieldService;

    @Resource
    private ProcessesService processesService;

    @Resource
    private DashboardService dashboardService;

    @Resource
    private AssemblyWorkOrderDetailMapper assemblyDetailMapper;

    /**
     * @param assemblyId         装配工单id
     * @param getProcessProgress 是否获取工序详情
     * @return 工单详情信息
     */
    public List<AssemblyDetailProductVo> getDetailByAssemblyId(Long assemblyId, boolean getProcessProgress) {
        ColumnUtils productColumnUtils = new ColumnUtils(customFieldService, ObjectType.product.getCode());
        List<AssemblyDetailProductVo> data = assemblyDetailMapper.getDetailByAssemblyId(assemblyId);
        Map<String, List<ProcessStatisticsVo>> codeProcessMap = null;
        if (getProcessProgress) {
            Set<String> workOrderCodes = data.stream().map(AssemblyDetailProductVo::getWorkOrderCode).collect(Collectors.toSet());
            List<ProcessStatisticsVo> processData = dashboardService.getProcessesByOrderCodes(workOrderCodes);
            processData.forEach(i -> {
                i.setFinishRate(i.getPlanNum().compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : (i.getGoodNum().divide(i.getPlanNum(), 2, RoundingMode.HALF_UP)).multiply(BigDecimal.valueOf(100L)));
            });
            codeProcessMap = processData.stream().collect(Collectors.groupingBy(ProcessStatisticsVo::getWorkOrderCode));
        }
        Map<String, List<ProcessStatisticsVo>> finalCodeProcessMap = codeProcessMap;
        data.forEach(i -> {
            i.setCustomFieldVos(productColumnUtils.getCuColumnsByJsonArray(i.getProductOther()));
            if (getProcessProgress && Objects.nonNull(finalCodeProcessMap)) {
                i.setProduceProgress(finalCodeProcessMap.get(i.getWorkOrderCode()));
            }
        });
        return data;
    }
}
